/* global wc_checkout_params */
jQuery(function ($) {

    // wc_checkout_params is required to continue, ensure the object exists
    if (typeof wc_checkout_params === 'undefined') {
        return false;
    }

    $.blockUI.defaults.overlayCSS.cursor = 'default';

    var wc_checkout_form = {
        updateTimer: false,
        dirtyInput: false,
        xhr: false,
        $order_review: $('#order_review'),
        $checkout_form: $('form.checkout'),
        init: function () {
            $(document.body).on('init_checkout', this.init_checkout);

            // Payment methods
            this.$checkout_form.on('click', 'input[name="payment_method"]', this.payment_method_selected);

            if ($(document.body).hasClass('woocommerce-order-pay')) {
                this.$order_review.on('click', 'input[name="payment_method"]', this.payment_method_selected);
            }

            // Inline validation
            this.$checkout_form.on('blur change', '.input-text, select, input:checkbox', this.validate_field);

            // Inputs/selects which update totals
            this.$checkout_form.on('change', '.address-field select', this.input_changed);
            this.$checkout_form.on('change', '.address-field input.input-text, .update_totals_on_change input.input-text', this.maybe_input_changed);
            this.$checkout_form.on('change keydown', '.address-field input.input-text, .update_totals_on_change input.input-text', this.queue_update_checkout);

            // Address fields
            this.$checkout_form.on('change', '#ship-to-different-address input', this.ship_to_different_address);

            // Trigger events
            this.$checkout_form.find('#ship-to-different-address input').change();
            this.init_payment_methods();

            // Update on page load
            if (wc_checkout_params.is_checkout === '1') {
                $(document.body).trigger('init_checkout');
            }
            if (wc_checkout_params.option_guest_checkout === 'yes') {
                $('input#createaccount').change(this.toggle_create_account).change();
            }
        },
        init_payment_methods: function (selectedPaymentMethod) {
            var $payment_methods = $('.woocommerce-checkout').find('input[name="payment_method"]');

            // If there is one method, we can hide the radio input
            if (1 === $payment_methods.length) {
                $payment_methods.eq(0).hide();
            }

            // If there was a previously selected method, check that one.
            if (selectedPaymentMethod) {
                $('#' + selectedPaymentMethod).prop('checked', true);
            }

            // If there are none selected, select the first.
            if (0 === $payment_methods.filter(':checked').length) {
                $payment_methods.eq(0).prop('checked', true);
            }

            // Trigger click event for selected method
            $payment_methods.filter(':checked').eq(0).trigger('click');
        },
        get_payment_method: function () {
            return wc_checkout_form.$order_review.find('input[name="payment_method"]:checked').val();
        },
        payment_method_selected: function () {
            if ($('.payment_methods input.input-radio').length > 1) {
                var target_payment_box = $('div.payment_box.' + $(this).attr('ID'));

                if ($(this).is(':checked') && !target_payment_box.is(':visible')) {
                    $('div.payment_box').filter(':visible').slideUp(250);

                    if ($(this).is(':checked')) {
                        $('div.payment_box.' + $(this).attr('ID')).slideDown(250);
                    }
                }
            } else {
                $('div.payment_box').show();
            }

            if ($(this).data('order_button_text')) {
                $('#place_order').val($(this).data('order_button_text'));
            } else {
                $('#place_order').val($('#place_order').data('value'));
            }
        },
        toggle_create_account: function () {
            $('div.create-account').hide();

            if ($(this).is(':checked')) {
                $('div.create-account').slideDown();
            }
        },
        init_checkout: function () {
            $('#billing_country, #shipping_country, .country_to_state').change();
        },
        maybe_input_changed: function (e) {
            if (wc_checkout_form.dirtyInput) {
                wc_checkout_form.input_changed(e);
            }
        },
        input_changed: function (e) {
            wc_checkout_form.dirtyInput = e.target;
            wc_checkout_form.maybe_update_checkout();
        },
        queue_update_checkout: function (e) {
            var code = e.keyCode || e.which || 0;

            if (code === 9) {
                return true;
            }

            wc_checkout_form.dirtyInput = this;
            wc_checkout_form.reset_update_checkout_timer();
            wc_checkout_form.updateTimer = setTimeout(wc_checkout_form.maybe_update_checkout, '1000');
        },
        maybe_update_checkout: function () {
            var update_totals = true;

            if ($(wc_checkout_form.dirtyInput).length) {
                var $required_inputs = $(wc_checkout_form.dirtyInput).closest('div').find('.address-field.validate-required');

                if ($required_inputs.length) {
                    $required_inputs.each(function () {
                        if ($(this).find('input.input-text').val() === '') {
                            update_totals = false;
                        }
                    });
                }
            }
        },
        ship_to_different_address: function () {
            $('div.shipping_address').hide();
            if ($(this).is(':checked')) {
                $('div.shipping_address').slideDown();
            }
        },
        reset_update_checkout_timer: function () {
            clearTimeout(wc_checkout_form.updateTimer);
        },
        validate_field: function () {
            var $this = $(this),
                $parent = $this.closest('.form-row'),
                validated = true;

            if ($parent.is('.validate-required')) {
                if ('checkbox' === $this.attr('type') && !$this.is(':checked')) {
                    $parent.removeClass('woocommerce-validated').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                    validated = false;
                } else if ($this.val() === '') {
                    $parent.removeClass('woocommerce-validated').addClass('woocommerce-invalid woocommerce-invalid-required-field');
                    validated = false;
                }
            }

            if ($parent.is('.validate-email')) {
                if ($this.val()) {

                    /* https://stackoverflow.com/questions/2855865/jquery-validate-e-mail-address-regex */
                    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);

                    if (!pattern.test($this.val())) {
                        $parent.removeClass('woocommerce-validated').addClass('woocommerce-invalid woocommerce-invalid-email');
                        validated = false;
                    }
                }
            }

            if (validated) {
                $parent.removeClass('woocommerce-invalid woocommerce-invalid-required-field').addClass('woocommerce-validated');
            }
        }
    };

    var wc_checkout_coupons = {
        init: function () {
            $(document.body).on('click', 'a.showcoupon', this.show_coupon_form);
            $('form.checkout_coupon').hide().submit(this.submit);
        },
        show_coupon_form: function () {
            $('.checkout_coupon').slideToggle(400, function () {
                $('.checkout_coupon').find(':input:eq(0)').focus();
            });
            return false;
        }
    };

    var wc_checkout_login_form = {
        init: function () {
            $(document.body).on('click', 'a.showlogin', this.show_login_form);
        },
        show_login_form: function () {
            $('form.login').slideToggle();
            return false;
        }
    };

    wc_checkout_form.init();
    wc_checkout_coupons.init();
    wc_checkout_login_form.init();
});
